package com.woniu.zsd.order.consumer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.woniu.commons.util.RedisKey;
import com.woniu.zsd.order.config.MyWebSocketHandler;
import com.woniu.zsd.order.entity.OrderInfo;
import com.woniu.zsd.order.mapper.OrderInfoMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component("orderRabbitMQConsumer")
public class RabbitMQConsumer {
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private MyWebSocketHandler myWebSocketHandler;

    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(name = "exchange1"),
                    value = @Queue(name = "queue1"),
                    key = "timeout"
            )
    })
    @RabbitHandler
    public void siteAllocationOrder(String orderNumber) {
        System.out.println(orderNumber);
        RLock lock = redissonClient.getLock(orderNumber);
        try {
            lock.lock(5, TimeUnit.SECONDS);
            QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_number",orderNumber);
            OrderInfo orderInfo = orderInfoMapper.selectOne(wrapper);
            if(orderInfo.getOrderState()==7){
                String s = stringRedisTemplate.opsForList().leftPop(RedisKey.SITA_LIST(orderNumber));
                if(s==null){
                    System.out.println("站点没有接单让管理员干涉");
                    orderInfoMapper.updateOrderState(orderNumber);
                    stringRedisTemplate.opsForValue().set(RedisKey.ORDERNUM_ADMIN_KEY(orderNumber),"手动处理",10, TimeUnit.MINUTES);
                    //消息推送到超级管理员手动处理
                    myWebSocketHandler.sendPointToPointMessage("1","有未分配订单请处理");
                    Boolean key = stringRedisTemplate.hasKey(RedisKey.ORDERNUM_ADMIN_KEY(orderNumber));
                    if(!key){
                       if(orderInfo.getOrderState()==7){
                           orderInfoMapper.update(null,new UpdateWrapper<OrderInfo>().eq("order_number",orderNumber)
                                   .set("order_state",6)
                                   .set("remarks","站点繁忙无法为您分配回收人员"));
                       }
                    }
                }else {
                    System.out.println("当前站点没有分配订单，取出其他站点分配");
                    Integer siteId = Integer.valueOf(s);
                    orderInfoMapper.update(null,new UpdateWrapper<OrderInfo>().eq("order_number",orderNumber)
                            .set("site_id",siteId));
                    rabbitTemplate.convertAndSend("site-expired-queue",orderNumber);
                    myWebSocketHandler.sendPointToPointMessage(s,"你被分配到新的订单请处理");
                }
            }else {
                System.out.println("站点分配了订单或者用户取消订单删除待分配列表");
                stringRedisTemplate.delete(RedisKey.SITA_LIST(orderNumber));
            }
        } catch (IOException | AmqpException | NumberFormatException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
}
